<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Electron + WASM</title>
    <style>
        .row {
            display: flex;
        }
    </style>
</head>
<body>
    <h2>WASM 计算器</h2>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <input type="number" id="number1" placeholder="请输入一个数字"> + 
                <input type="number" id="number2" placeholder="请输入一个数字"> =
            </div>
            <div class="col-md-6">
                <div><input type="text" id="resultRender" readonly placeholder="渲染进程结果"></div>
                <div><input type="text" id="resultMain" readonly placeholder="主进程结果"></div>
            </div>
        </div>
    </div>

    <script type="module">
        // 导入 WASM 模块
        import Module from './dist/web/calculator.js';

        // 初始化模块
        const wasmModule = await Module();

        // 设置事件监听器
        document.getElementById('number1').addEventListener('change', () => {
            sum();
        });

        document.getElementById('number2').addEventListener('change', () => {
            sum();
        });

        // 新增的主进程通信逻辑
        const { ipcRenderer } = require('electron');

        async function sum() {
            const num1 = Number(document.getElementById('number1').value);
            const num2 = Number(document.getElementById('number2').value);
            const resultRender = document.getElementById('resultRender');
            const resultMain = document.getElementById('resultMain');

            // 验证输入
            if (!num1 || !num2) {
                resultRender.value = '请输入两个数字';
                return;
            }

            try {
                // 通过IPC发送计算请求到主进程
                ipcRenderer.invoke('calculate-add', num1, num2).then(res => {
                    // 检查是否有错误
                    if (res && res.error) {
                        resultMain.value = `错误: ${res.error}`;
                    } else {
                        resultMain.value = res.result;
                    }
                })

                // 渲染进程计算
                resultRender.value = wasmModule.add(num1, num2);
            } catch (error) {
                resultMain.value = `计算失败: ${error.message}`;
            }
        }
    </script>
</body>
</html>